package com.xx.dk.tbsalling.aismessages.ais.messages.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xx.dk.tbsalling.aismessages.ais.messages.AISMessage;
import com.xx.dk.tbsalling.aismessages.ais.messages.ShipAndVoyageData;
import com.xx.domain.ShipBaseInfo;
import com.xx.netty.server.constants.AisConstants;
import com.xx.utils.redis.RedisUtil;
import com.xx.web.domain.entity.ZlShip;
import com.xx.web.mapper.ZlShipMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @description: 05 静态和航程相关数据
 * @author: xx
 * @Date 2023/7/6
 */
@Component
@RequiredArgsConstructor
public class ShipAndVoyageDataHandler implements AISMessageHandler {

    private final RedisUtil redisUtil;
    private final ZlShipMapper shipMapper;

    //if (msgType == 5 || msgType == 6 || msgType == 10 || msgType == 11 || msgType == 24)
    @Override
    public void handle(AISMessage message) {
        ShipAndVoyageData data = (ShipAndVoyageData) message;
        //System.out.println(data.getMessageType().getCode() +"-----" + data.toString());
        //get data from the redis
        Integer mmsi = data.getSourceMmsi().getMMSI();
        if (mmsi == 0) {
            return;
        }
        ShipBaseInfo info = redisUtil.get(AisConstants.AIS_SHIP_INFO + mmsi);
        if (info == null) { //baseInfo is null,so new and assemble the data
            cacheRedis(data, mmsi);
        }else{
           /* if (StringUtils.isBlank(info.getName())) {
                cacheRedis(data, mmsi);
            }*/
            ShipBaseInfo shipBaseInfo = new ShipBaseInfo(data);
            shipBaseInfo.setChineseName(info.getChineseName());
            shipBaseInfo.setRegion(info.getRegion());
            redisUtil.set(AisConstants.AIS_SHIP_INFO + mmsi, shipBaseInfo, 86400L * 7);
        }
    }

    private void cacheRedis(ShipAndVoyageData data, Integer mmsi) {
        ShipBaseInfo baseInfo = new ShipBaseInfo(data);
        ZlShip zlShip =
                shipMapper.selectOne(Wrappers.<ZlShip>lambdaQuery().select(ZlShip::getLocalName,
                        ZlShip::getFlagCode).eq(StringUtils.isNotBlank(baseInfo.getName()),ZlShip::getShipNameEn, baseInfo.getName()).or().eq(ZlShip::getMmsi,mmsi).last("limit 1"));
           /* ZlShip zlShip =
                    shipMapper.selectOne(Wrappers.<ZlShip>lambdaQuery().select(ZlShip::getLocalName).eq
                    (ZlShip::getMmsi, baseInfo.getMmsi()).last("limit 1"));*/
        baseInfo.setZlShip(zlShip);
        //cached redis
        redisUtil.set(AisConstants.AIS_SHIP_INFO + mmsi, baseInfo, 86400L * 5);
   /*     if (zlShip != null && StringUtils.isNotBlank(zlShip.getLocalName())) {
            redisUtil.set(AisConstants.SHIP_CHINESE + mmsi, zlShip.getLocalName());
        }*/

    }

    private static final String BOAT_INFO_SET_KEY = "boat_info_set";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void cacheBoatInfo(String boatId, String boatInfo, long expireTime) {
        // 将船只信息添加到有序集合中，并设置过期时间
        redisTemplate.opsForZSet().add(BOAT_INFO_SET_KEY, boatId, expireTime);

        // 将船只信息保存到 Redis 中，并设置过期时间
        String boatInfoKey = "boat_info:" + boatId;
        redisTemplate.opsForValue().set(boatInfoKey, boatInfo);
        redisTemplate.expire(boatInfoKey, expireTime, TimeUnit.SECONDS);
    }

    public String getBoatInfo(String boatId) {
        // 从 Redis 中获取船只信息
        String boatInfoKey = "boat_info:" + boatId;
        return redisTemplate.opsForValue().get(boatInfoKey);
    }

    public void deleteExpiredBoatInfo() {
        // 删除过期的船只信息
        long currentTimestamp = System.currentTimeMillis() / 1000;
        redisTemplate.opsForZSet().removeRangeByScore(BOAT_INFO_SET_KEY, 0, currentTimestamp);
    }
}
